# coding: utf-8

import os
import random
import time

import config
import handler.http as httpHandler
import handler.image as imageHandler
import handler.jsonp as jsonHandler
from handler.cookie import CookieHandler
from handler.database import (DatabaseHandler, InsuranceType, PolicyRecord)
from handler.file import FileHandler
from model.attribute_dict import AttributeDict
from model.entity import Entity
from model.utils import current_timestamp
from handler.selenium_handler import By, SeleniumHandler

from . import logger


class RenbaoSpider(object):
    def __init__(self, file_handler=None):
        self.user_login_account = '17080050605'
        self.user_login_password = 'cgmY4699'
        self.user_login_type = 'loginBySample'
        self.base_url = 'http://www.epicc.com.cn'
        self.login_url = '{0}/idprovider/views/login.jsp'.format(self.base_url)
        self.login_post_url = '{0}/idprovider/login'.format(self.base_url)
        self.login_init_captcha_url = '{0}/idprovider/initCaptcha'.format(self.base_url)
        self.login_check_captcha_url = '{0}/idprovider/checkCaptcha'.format(self.base_url)
        self.service_url = '{0}/fuwu/'.format(self.base_url)
        self.target_query_url = '{0}/fuwu/chexianbaodanlipei/'.format(self.base_url)
        self.target_result_url = '{0}/ecenter/policyModule/Policy/carPolicyDetail'.format(self.base_url)
        self.target_verify_code_url = self.base_url + '/ecenter/CreateImage?randName=verifypicForCar&next={0}'
        self.target_verify_code_check_url = '{0}/ecenter/insuringAndClaims/PolicyClaimCheck/policyClaimNewIndex/checkNewRandCode'.format(self.base_url)
        self.target_verify_code_check_url_one = '{0}/newecenter/carPolicyQuery/checkValidCode.do'.format(self.base_url)
        self.download_verify_code_image_referer = '{0}/ecenter/views/insuringAndClaims/insurAndClaimsforIndex/claimEntranceClub.jsp'.format(self.base_url)
        self.__initialize(file_handler=file_handler)

    def __initialize(self, file_handler=None):
        self.cookie_name = 'renbao'
        self.header = config.HEADER
        self.header['Host'] = self.base_url.replace('http://', '')
        self.header['Origin'] = self.base_url
        self.start_url = self.service_url
        self.database = DatabaseHandler()
        if file_handler is None:
            file_handler = FileHandler()
        self.file_handler = file_handler
        self.cookie_handler = CookieHandler()

    def __set_cookie_list(self, cookies):
        self.cookie_handler.set_cookie_list(self.cookie_name, cookies)

    def __get_cookie_to_string(self):
        return self.cookie_handler.get_cookie_to_string(self.cookie_name)

    def __get_cookie_to_list(self):
        return self.cookie_handler.get_cookie_to_list(self.cookie_name)

    def __get_cookie_to_dict(self):
        return self.cookie_handler.get_cookie_to_dict(self.cookie_name)

    def __get(self, url):
        self.selenium = SeleniumHandler()
        self.selenium.maximize_window()
        self.selenium.get(url)
        cookies = self.__get_cookie_to_list()
        if cookies:
            self.selenium.add_cookie(cookies)
        self.header['Cookie'] = self.__get_cookie_to_string()
        self.selenium.add_header(config.HEADER)
        time.sleep(1)

    def __get_url(self):
        current_url = self.selenium.get_current_url()
        index = current_url.find('?')
        if index > -1:
            current_url = current_url[0:index]
        return current_url

    ''' 通过链接下载图形验证码 '''
    def __download_to_image(self, url):
        header_new = self.header
        header_new['Cookie'] = self.__get_cookie_to_string()
        header_new['Referer'] = self.download_verify_code_image_referer
        return imageHandler.download_to_image(url, headers=header_new, cookies=self.__get_cookie_to_dict())

    ''' 从页面裁剪出图形验证码 '''
    def __get_verify_code_image(self, element):
        size = element.size
        location = element.location
        top = int(location['y']) + 200
        left = int(location['x']) + 618
        right = int(left + size['width'])
        bottom = int(top + size['height'])
        data = self.selenium.get_screenshot_as_png()
        image = imageHandler.data_to_image(data)
        return imageHandler.cut_verify_code_image(image, (left, top, right, bottom ))

    ''' 图形验证码是否通过验证 '''
    def __is_verify_code_success(self, code):
        header_new = self.header
        header_new['Cookie'] = self.__get_cookie_to_string()
        header_new['X-Requested-With'] = 'XMLHttpRequest'
        response = httpHandler.post(self.target_verify_code_check_url,
                         data={ 'pageRandCode': code },
                         headers=header_new,
                         cookies=self.__get_cookie_to_dict())
        try:
            verify_ret = int(response.text)
            return verify_ret == 1
        except Exception as e:
            logger.error(u'校验验证码异常:{0}'.format(e))
        return False

    ''' 图形验证码是否通过验证 '''
    def __is_verify_code_success_one(self, code):
        header_new = self.header
        header_new['Cookie'] = self.__get_cookie_to_string()
        header_new['X-Requested-With'] = 'XMLHttpRequest'
        url = self.target_verify_code_check_url_one + '?time={0}&validCode={1}'.format(current_timestamp(), code)
        response = httpHandler.get(url, headers=header_new, cookies=self.__get_cookie_to_dict())
        try:
            return response.text == 'true'
        except Exception as e:
            logger.error(u'校验验证码异常:{0}'.format(e))
        return False

    ''' 获取滑动验证滑块的x目标距离 '''
    def __get_captcha_slide_x(self):
        # 获取滑块
        # verify_code_slide_style = self.selenium.get_element_attribute('//*[@id="validateBox"]', 'style')
        # verify_code_slide_url_match = STYLE_URL_PATTERN.match(verify_code_slide_style)
        # if not verify_code_slide_url_match:
        #     logger.info(u'未获取到图形滑块标识')
        #     return
        # verify_code_slide_url = '{0}{1}'.format(self.base_url, verify_code_slide_url_match.group('url'))
        # 获取原背景
        verify_code_background_style = self.selenium.get_element_attribute('//*[@id="captchaBoxCont"]', 'style')
        verify_code_background_url_match = config.STYLE_URL_PATTERN.match(verify_code_background_style)
        if not verify_code_background_url_match:
            logger.info('not getting the login captcha old background!')
            return
        verify_code_background_url = '{0}{1}'.format(self.base_url, verify_code_background_url_match.group('url'))
        self.slide_bar_element = self.selenium.get_element('//*[@id="slideBar"]')
        self.slide_bar_element.click()
        # 获取背景
        verify_code_new_background_style = self.selenium.get_element_attribute('//*[@id="captchaBoxCont"]', 'style')
        verify_code_new_background_url_match = config.STYLE_URL_PATTERN.match(verify_code_new_background_style)
        if not verify_code_new_background_url_match:
            logger.info('not getting the login captcha new background!')
            return
        verify_code_new_background_url = '{0}{1}'.format(self.base_url, verify_code_new_background_url_match.group('url'))
        time.sleep(2)
        # logger.info(u'滑块:{0}'.format(verify_code_slide_url))
        # logger.info(u'原背景'.format(verify_code_background_url))
        # logger.info(u'新背景'.format(verify_code_new_background_url))
        verify_code_background_image = imageHandler.download_to_image(verify_code_background_url)
        verify_code_new_background_image = imageHandler.download_to_image(verify_code_new_background_url)
        verify_code_slide_target_location_x = imageHandler.get_diff_location(verify_code_background_image, verify_code_new_background_image)
        logger.info('login captcha slide target x location:{0}'.format(verify_code_slide_target_location_x))
        return verify_code_slide_target_location_x

    ''' 登陆成功后保存cookie '''
    def __remember_login_cookie(self):
        cookies = self.selenium.get_cookies()
        self.cookie_handler.set_cookie_list(self.cookie_name, cookies)
        self.selenium.add_cookie(cookies)

    ''' 滑动验证模拟滑动 - 假的 '''
    def __captcha_imitate_slide(self):
        self.action_chains = self.selenium.get_action_chains()
        verify_code_slide_target_location_x = self.__get_captcha_slide_x()
        self.action_chains.click_and_hold(self.slide_bar_element).perform()
        time.sleep(1)
        verify_code_slide_target_location_x -= 10
        for i in range(verify_code_slide_target_location_x):
            javascript_string = '''
                    $('#captchaBox').attr('display', 'block');
                    $('#slideBar').css('left', '{0}px');
                    $('#validateBox').css('left', '{0}px');
                    $('.slide-box-b').css('width', '{0}px');'''.format(i)
            self.selenium.execute_script(javascript_string)
            time.sleep(random.randint(30, 60) / 100)

    ''' 滑动验证模拟验证成功 - 假的 '''
    def __captcha_imitate_success(self):
        try:
            self.selenium.execute_script('''
                isCheckSuccess = !0;
                dragStatus = !0;
                showImgBack();
                $sliderBar.attr("class", "slide-bar");
                $validateBox.removeClass("active");
                $validateBox.css({display: "none"});
                $guang.animate({ right: "305px" }, 600, function() {
                    $guang.css({ right: "-305px" })
                });
                $slideBox.find(".slide-tip").html('<img src="/idprovider/images/images/success_bg_text.png" alt="">');
                $(".slide-tip").fadeIn();
                $sliderBar.animate({ left: "236px" }, 300);
                $(".captcha-tips-suc").fadeIn();
                changeSendSmsBtnStatus();''')
        except Exception as e:
            logger.error('login captcha imitate success, error:{0}'.format(e))

    ''' 分析验证算法, 进行请求模拟 '''
    def __captcha_crack_general(self, challenge_id, headers):
        jquery_callback_prefix = self.selenium.execute_script('return jQuery.expando;')
        jquery_callback_func_name = '{0}_{1}'.format(jquery_callback_prefix, current_timestamp())
        init_captcha_url = self.login_init_captcha_url
        init_captcha_url += '?challenge={0}'.format(challenge_id)
        init_captcha_url += '&jsoncallback={0}'.format(jquery_callback_func_name)
        response = httpHandler.post(init_captcha_url, headers=headers, cookies=self.__get_cookie_to_dict())
        jquery_callback_match = config.JQUERY_CALLBACK_PATTERN.match(response.text)
        jquery_callback_dict = jsonHandler.to_object(jquery_callback_match.group('json'))
        captcha = jquery_callback_dict['captcha']
        slide_x = int(captcha['slideX'])
        slide_y = int(captcha['slideY'])
        self.__captcha_imitate_slide()
        def get_captcha_data(x, y):
            slpit_list, x_list, y_list, mouse_time_list = [], [], [], []
            init_x = 1106
            init_y = 315 + y
            x_random_number = random.randint(1, 3)
            while (x - x_random_number) >= 0:
                slpit_list.append(',')
                init_x += x_random_number
                x_list.append(init_x)
                y_list.append(init_y + random.randint(-5, 5))
                mouse_time_list.append(current_timestamp())
                x -= x_random_number
                x_random_number = random.randint(1, 3)
                time.sleep(random.randint(5, 10) / 100.0)
            slpit_list = slpit_list[0: (len(slpit_list) - 1)]
            return (slpit_list, x_list, y_list, mouse_time_list)
        slide_data_tuple = get_captcha_data(slide_x, slide_y)
        slpit_string = ''.join(slide_data_tuple[0])
        x_string = ','.join(str(s) for s in slide_data_tuple[1])
        y_string = ','.join(str(s) for s in slide_data_tuple[2])
        time_string = ','.join(str(s) for s in slide_data_tuple[3])
        check_captcha_url = self.login_check_captcha_url
        check_captcha_url += '?challenge={0}'.format(challenge_id)
        check_captcha_url += '&pageX={0}'.format(slide_x)
        check_captcha_url += '&typeMouse={0}'.format(slpit_string)
        check_captcha_url += '&pageXAxis={0}'.format(x_string)
        check_captcha_url += '&pageYAxis={0}'.format(y_string)
        check_captcha_url += '&mouseTime={0}'.format(time_string)
        check_captcha_url += '&jsoncallback={0}'.format(jquery_callback_func_name)
        response = httpHandler.post(check_captcha_url, headers=headers, cookies=self.__get_cookie_to_dict())
        jquery_callback_match = config.JQUERY_CALLBACK_PATTERN.match(response.text)
        jquery_callback_dict = jsonHandler.to_object(jquery_callback_match.group('json'))
        return str(jquery_callback_dict['captcha']['statusCode']) == 'success'

    ''' 登陆-常规post, 跳过页面表单提交 '''
    def __login_general(self):
        logger.info('start login general, begin...')
        headers_new = self.header
        headers_new['X-Requested-With'] = 'XMLHttpRequest'
        challenge_id = self.selenium.get_element_attribute('//*[@id="challengeID"]', 'value')
        is_captcha = self.__captcha_crack_general(challenge_id, headers=headers_new)
        if is_captcha:
            logger.info('login captcha verify success!')
            self.__captcha_imitate_success()
            script_string = 'enceypt("MUserCode","MPassword","{0}","{1}");return get32Md5Str(navigator.userAgent);'
            user_agent = self.selenium.execute_script(script_string.format(self.user_login_account, self.user_login_password))
            user_name = self.selenium.get_element_attribute('//*[@id="MUserCode"]', 'value')
            user_password = self.selenium.get_element_attribute('//*[@id="MPassword"]', 'value')
            user_password_key = self.selenium.get_element_attribute('//*[@id="psw"]', 'value')
            response = httpHandler.post(self.login_post_url, data={
                'rand': challenge_id,
                'userName': user_name,
                'password': user_password,
                'pswkey': user_password_key,
                'loginType': self.user_login_type,
                'userAgent': user_agent,
            }, headers=headers_new, cookies=self.__get_cookie_to_dict())
            user_data_dict = jsonHandler.to_object(response.text)
            self.file_handler.write_user_data(user_data_dict)
            cookies = self.cookie_handler.tuples_to_list(response.cookies.items())
            self.__set_cookie_list(cookies)
            self.selenium.add_cookie(cookies)
            self.selenium.jump_page(self.service_url)
            self.__service_page()
            self.__remember_login_cookie()
            logger.info('start login general, end!')
            time.sleep(1)
        else:
            logger.info('login captcha verify failed!')
            self.__login_page()

    ''' 滑动验证模拟破解 '''
    def __captcha_crack_imitate(self):
        self.action_chains = self.selenium.get_action_chains()
        verify_code_slide_target_location_x = self.__get_captcha_slide_x()
        while verify_code_slide_target_location_x is None:
            verify_code_slide_target_location_x = self.__get_captcha_slide_x()
        # 根据缺口的位置模拟x轴移动的轨迹
        def get_track(size):
            list = []
            last_number = 3
            random_x = random.randint(1, 3)
            while (size - random_x) >= last_number:
                list.append(random_x)
                size = size - random_x
                random_x = random.randint(1, 3)
            return list
        location_x_list = get_track(verify_code_slide_target_location_x)
        self.action_chains.click_and_hold(self.slide_bar_element).perform()
        for x in location_x_list:
            self.action_chains.move_by_offset(x, random.randint(-5, 3)).perform()
            self.action_chains.reset_actions()
            time.sleep(random.randint(10, 30) / 100)
        for _ in range(4):
            self.action_chains.move_by_offset(-1, random.randint(-5, 3)).perform()
            time.sleep(random.randint(10, 30) / 100)
        logger.debug('login captcha slide last location:{0}'.format(self.slide_bar_element.location))
        self.action_chains.release().perform()
        time.sleep(1)
        return self.selenium.execute_script('return isCheckSuccess;')

    ''' 从页面登陆模拟 '''
    def __login_imitate(self):
        logger.info('start login imitate, begin...')
        while True:
            if self.__captcha_crack_imitate() is False:
                try:
                    self.selenium.get_element('//*[@id="refreshBtn"]').click()
                except Exception as e:
                    logger.error(e)
                time.sleep(1)
                continue
            else:
                break
        self.selenium.get_element('//*[@id="epiccLogin"]').click()
        time.sleep(1)
        self.__remember_login_cookie()
        logger.info('start login imitate, end!')

    ''' 登陆页面 '''
    def __login_page(self):
        logger.info('get into login page, ready login!')
        self.selenium.get_element('/html/body/div[1]/div[2]/div/div[2]/div/div[2]/ul/li[2]').click()
        self.selenium.execute_script('$("entryId").val("");$("password").val("");')
        self.selenium.get_element('//*[@id="entryId"]').send_keys(self.user_login_account)
        self.selenium.get_element('//*[@id="password"]').send_keys(self.user_login_password)
        # self.__login_general()
        self.__login_imitate()
        logger.info('login success!', split=True)

    ''' 回到服务中心页面, 尝试通过点击页面按钮进入[车险保单理赔查询] '''
    def __service_page(self):
        script = self.selenium.get_element_attribute('/html/body/div[3]/div/div/div[2]/div[1]/div/dl[4]/dt/a', 'onclick')
        self.selenium.execute_script(script)
        time.sleep(1)

    ''' 图形验证码破解 '''
    def __verify_code_crack(self):
        input_verify_code = self.selenium.get_element('//*[@id="cpq_validCode"]')
        verify_code_element = self.selenium.get_element('//*[@id="cpq_validCode_img"]')
        link_refresh_verify_code = verify_code_element
        # link_refresh_verify_code = self.selenium.get_element('//*[@id="randForClaimEntrance"]')
        # 验证码自动识别验证
        verify_error_number = 0
        while True:
            # verify_code_url = verify_code_element.get_attribute('src')
            # verify_code_image = self.__download_to_image(verify_code_url)
            verify_code_image = self.__get_verify_code_image(verify_code_element)
            verify_code_string = imageHandler.image_to_string(verify_code_image)
            verify_result = self.__is_verify_code_success_one(verify_code_string)
            verify_mesage = 'verify code: [{0}] | verify result: {1}'
            if verify_result is True:
                logger.info(verify_mesage.format(verify_code_string, 'success!'))
                input_verify_code.send_keys(verify_code_string)
                return True
            else:
                logger.info(verify_mesage.format(verify_code_string, 'verify code identify failed, waiting for reidentifying!'))
                verify_error_number += 1
                # 错误次数过多, 重新获取cookie
                if verify_error_number >= config.QUERY_VERIFY_UPDATE_COOKIE_MAX_ERROR_NUMBER:
                    logger.info('update cookie, refresh page, reset query!')
                    cookies = self.selenium.get_cookies()
                    self.__set_cookie_list(cookies)
                    self.selenium.add_cookie(cookies)
                    return False
                # 错误次数过多, 删除cookie, 重新登陆
                if verify_error_number >= config.QUERY_VERIFY_RESET_LOGIN_MAX_ERROR_NUMBER:
                    logger.info('delete cookie, reset login, reset query!')
                    self.selenium.delete_all_cookie()
                    self.run(self.policy_no, self.idcard_no)
                    return None
                link_refresh_verify_code.click()
                time.sleep(1)

    ''' 进入目标查询页面 '''
    def __query_page(self, policy_no, idcard_no):
        logger.info('current query policy no: [{0}], idcard no: [{1}]'.format(policy_no, idcard_no))
        self.selenium.switch_to_default_content()
        target_iframe = self.selenium.get_element('//*[@id="iframepage"]')
        self.selenium.switch_to_frame(target_iframe)
        self.selenium.get_element('//*[@id="cpq_policyNo"]').send_keys(policy_no)
        self.selenium.get_element('//*[@id="cpq_identifyNo"]').send_keys(idcard_no)
        is_verify = self.__verify_code_crack()
        if is_verify is True:
            # submit_query_buttom = self.selenium.get_element('/html/body/div/div[2]/div[1]/ul/li[4]/input[1]')
            submit_query_buttom = self.selenium.get_element('//*[@id="cpq_policyBtn"]')
            # submit_query_buttom.click()
            # verify_code_error = self.selenium.execute_script('return $("#error_randCarClaimWrong b").text();')
            # if verify_code_error:
            #     self.selenium.refresh()
            #     self.__query_page(policy_no, idcard_no)
            #     return
            # 等待打开新页面
            for _ in range(10):
                submit_query_buttom.click()
                time.sleep(1)
                handles = self.selenium.get_windows()
                if len(handles) <= 1:
                    time.sleep(1)
                    continue
                self.query_handler = self.selenium.get_current_window()
                self.selenium.switch_to_window(handles[1])
                time.sleep(1)
                if self.__get_url() == self.target_result_url:
                    self.__result_page()
                break
        elif is_verify is False:
            self.selenium.refresh()
            self.__query_page(policy_no, idcard_no)
        else:
            pass

    ''' 进入目标结果页,开始采集数据 '''
    def __result_page(self):
        time.sleep(3)
        try:
            policy_record = PolicyRecord()
            policy_record.policy_no = self.policy_no
            if str(self.selenium.get_page_source()).find(u'未能查询到该保单') > -1:
                self.file_handler.write_queried(self.policy_no, 0)
                policy_record.status = 0
                self.database.insert(policy_record)
                logger.info('policy no [{0}] not found info!'.format(self.policy_no))
                return False
            try:
                self.selenium.wait((By.ID, 'tab_ke'))
            except Exception as e:
                logger.error(e)
                self.file_handler.write_queried(self.policy_no, -1)
                return False
            logger.info('policy no [{0}] queried info!'.format(self.policy_no))
            policy_info = AttributeDict()
            policy_info.policy_holder_name = self.selenium.get_element_text('//*[@id="tab_ke"]/div[2]/table[1]/tbody/tr[4]/td[4]')# 投保人姓名
            policy_info.policy_name = self.selenium.get_element_text('//*[@id="tab_ke"]/div[2]/table[1]/tbody/tr[2]/td[4]')# 险种名称
            policy_info.policy_no = self.selenium.get_element_text('//*[@id="policyNoForClaim"]')# 保单号
            policy_info.policy_date_time = self.selenium.get_element_text('//*[@id="tab_ke"]/div[2]/table[1]/tbody/tr[3]/td[2]')# 保险期间
            policy_info.policy_begin_date_time = self.selenium.get_element_text('//*[@id="tab_ke"]/div[2]/table[1]/tbody/tr[3]/td[4]')# 保险责任开始时间
            policy_info.policy_status = self.selenium.get_element_text('//*[@id="tab_ke"]/div[2]/table[1]/tbody/tr[4]/td[2]')# 保单状态
            policy_info.policy_the_name = self.selenium.get_element_text('//*[@id="tab_ke"]/div[2]/table[1]/tbody/tr[5]/td[2]')# 被保险人姓名
            policy_info.policy_the_no = self.selenium.get_element_text('//*[@id="identyNumberForClaim"]')# 被保险人证件号码
            policy_info.insurance_type_list = []
            table3_trs = self.selenium.get_elements('//*[@id="tab_ke"]/div[2]/table[3]/tbody/tr') #商品险种信息
            for (index, tr) in enumerate(table3_trs):
                if index == 0:
                    continue
                table3_tds = tr.find_elements_by_tag_name('td')
                # insurance_type = InsuranceType()
                insurance_type = AttributeDict()
                insurance_type.guarantee_project = table3_tds[0].text # 保障项目
                insurance_type.sum_insured = table3_tds[1].text # 保额
                insurance_type.annual_premium = table3_tds[2].text # 标准保费
                insurance_type.rate_floating_coefficient = table3_tds[3].text # 费率浮动系数
                insurance_type.payment_premium = table3_tds[4].text # 实缴保费
                rate_floating_cause = table3_tds[5].text # 费率浮动事由
                if rate_floating_cause:
                    insurance_type.rate_floating_cause = rate_floating_cause.replace(os.linesep, '.')
                policy_info.insurance_type_list.append(insurance_type)
            table2_tds = self.selenium.get_elements('//*[@id="tab_ke"]/div[2]/table[2]/tbody/tr[3]/td')
            policy_info.license_plate_no = table2_tds[0].text # 车牌号
            policy_info.frame_number = table2_tds[1].text # 车架号
            policy_info.engine_number = table2_tds[2].text # 发动机号
            policy_info.nuclear_load_number = table2_tds[3].text # 核定载客数量
            policy_info.nuclear_load_weight = table2_tds[4].text # 核定载重质量
            policy_info.vehicle_type = table2_tds[5].text #车辆类型
            policy_info.vehicle_usage = table2_tds[6].text #车辆使用性质
            table4_tds = self.selenium.get_elements('//*[@id="tab_ke"]/div[2]/table[4]/tbody/tr[3]/td')
            policy_info.pay_premium = table4_tds[0].text # 应缴保费
            policy_info.paid_premium = table4_tds[1].text # 已缴保费
            policy_info.pay_method = table4_tds[2].text # 缴费方式
            policy_info.pay_date = table4_tds[3].text # 缴费日期
            policy_info.unpaid_premium = table4_tds[4].text # 欠缴保费
            table5_tds = self.selenium.get_elements('//*[@id="tab_ke"]/div[2]/table[5]/tbody/tr[3]/td')
            policy_info.channel_type = table5_tds[0].text # 渠道类型
            policy_info.agency_name = table5_tds[1].text # 代理机构/人名称
            policy_info.agency_code = table5_tds[2].text # 机构代码/职业资格证书代码
            policy_info.payment_method = table5_tds[3].text # 支付方式
            policy_info.payment_object = table5_tds[4].text # 支付对象
            self.file_handler.write_result_json(policy_info)
            # self.file_handler.write_result(policy_info)
            # self.database.insert_policy(policy_info)
            logger.info('policy no [{0}] save info!'.format(self.policy_no))
        finally:
            self.selenium.close().switch_to_window(self.query_handler).refresh()
            time.sleep(1)

    def __handler(self, policy_no, idcard_no):
        self.policy_no = policy_no
        self.idcard_no = idcard_no
        if self.__get_url() == self.service_url:
            self.__service_page()
        if self.__get_url() == self.login_url:
            self.__login_page()
        if self.__get_url() == self.target_query_url:
            self.__query_page(policy_no, idcard_no)
        logger.info('current query complete!', split=True)

    def run(self, policy_no, idcard_no):
        if self.file_handler.check_queried(policy_no):
            self.__get(self.start_url)
            self.__handler(policy_no, idcard_no)
            # self.selenium.close()
            self.exit()

    def batch_run(self, query_list):
        logger.info('total of {0} data!'.format(len(query_list)), split=True)
        self.__get(self.start_url)
        for (idcard_no, policy_no) in query_list:
            if self.file_handler.check_queried(policy_no):
                self.__handler(policy_no, idcard_no)
                time.sleep(1)
        self.exit()
        logger.info('all query complete!', split=True)

    def exit(self):
        self.selenium.exit()
